﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceApplication.Service.WorkFlow;
using OAclient.Models;
using CommonLibrary.DataModel.WorkFlow;
using CommonLibrary.DataModel.Form;
using ServiceApplication.Service;
using System.Xml.Linq;
using CommonLibrary.Common;
using CommonLibrary.Wf.InterFace;
using Bukovics.Workflow.Hosting;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using OAclient.Filters;
using System.Workflow.Activities;

namespace OAclient.Controllers
{
    [VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    public class PlanController : Controller
    {
        //
        //  plan流程特点：发起人发起，发起的时候选择处理人，如果多人，则发起多个流程
        //
        WorkFlowService wfs = new WorkFlowService();
        FormService fs = new FormService();
        SerializeDesigner designer = new SerializeDesigner();
        BasicService bs = new BasicService();
        public ActionResult PlanList(UserModel user)
        {
            var dt_wf = wfs.QueryWfByType("计划");
            ViewData["dt_wf"] = dt_wf;
            ViewData["user_id"] = user.user.user_id;
            return PartialView();
        }

        public ActionResult PlanCurTaskList(UserModel user)
        {
            var dt = wfs.QueryTaskForPlan(user.user.user_id.ToString(), "未处理");
            ViewData["dt"] = dt;
            return PartialView();
        }

        /// <summary>
        /// 显示一次计划发起（多人处理就有多条wfins，明细中显示）
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public ActionResult PlanStartList(UserModel user)
        {
            var dt = wfs.queryPlan(user.user.user_id.ToString());
            ViewData["dt"] = dt;
            return PartialView();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult PlanDetial(string ins_id)
        {
            var dt = wfs.queryPlanDetial(ins_id);
            ViewData["dt"] = dt;
            return PartialView();
        }


        public ActionResult PlanStart(string wf_id, string user_id)
        {
            if (string.IsNullOrEmpty(wf_id))
            {
                return Content("不存在wf_id");
            }
            if (string.IsNullOrEmpty(user_id))
            {
                return Content("不存在user_id");
            }
            UserEntity user = bs.QueryUser(int.Parse(user_id));
            StaffEntity se = bs.QueryStaff(user.staff_id);
            DeptEntity dept = bs.QueryDept(se.dept_id);
            DutyEntity duty = bs.QueryDuty(se.duty_id);
            WfEntity wfEntity = wfs.QueryWf(wf_id);
            FormEntity formEntity = fs.QueryFormEntity(wfEntity.form_id);

            if (formEntity == null)
            {
                return Content("不存在该表单");
            }
            ViewData["treevisible"] = "T";
            XElement xml = XElement.Load(Server.MapPath("~/UploadFiles/Form/" + formEntity.location));
            WorkFlowModel wfm = new WorkFlowModel();
            ViewData["formdefi"] = designer.DeserializeXmlToWeb(xml, new SerializeAutoData(true) { user_name = user.user_name, user_deptname = dept.dept_name, user_dutyname = duty.duty_name, user_id = user.user_id.ToString() });
            ViewData["form_id"] = formEntity.form_id.ToString();
            ViewData["wftemplate_id"] = wfEntity.wftemplate_id.ToString();
            ViewData["wf_id"] = wfEntity.wf_id.ToString();


            #region 获取下一步处理人类型
            //WfClrxxInfo nextClr = wfs.getClrxxByFirstNext(
            //    (System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>), wfEntity.wftemplate_id);
            ////初始化选择树
            //ViewData["treedefi"] = ZTreeHelper.Serialize(bs.GetWebUserNodeList());

            //if (nextClr != null)
            //{
            //    if (nextClr.clzType == TaskClrType.由上一步处理人指定.ToString())
            //    {
            //        ViewData["treevisible"] = "T";
            //    }
            //    else //特殊情况：ifelse活动的下一步处理人无法获取，所以不是 由上一步处理人指定 的情况，在createWorkflow 方法中clr传入null
            //    {
            //        ViewData["treevisible"] = "F";
            //    }
            //}
            #endregion

            return PartialView(wfm);
        }

        #region 方法

        //为每个处理人都发起一个流程
        public ActionResult DoPlanStart(UserModel user)
        {
            string wf_name = Request["wf_name"];
            string form_id = Request["form_id"];
            string wftempid = Request["wftemplate_id"];
            string wf_id = Request["wf_id"];
            string sqlargs = Request["sqlargs"];
            int[] clrs = null;//计划中clr是必须选择的，所以页面提交时需要判定
            if (!string.IsNullOrEmpty(Request["selectarr"]))
            {
                string[] selectarr = Request["selectarr"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                clrs = Array.ConvertAll<string, int>(selectarr, delegate(string s) { return int.Parse(s); });
            }

            List<FormFieldEntity> ffeList = new FormService().QueryFormFieldEntitys(int.Parse(form_id), "text");//表单字段实体List
            List<WfInsvalueEntity> wivList = new List<WfInsvalueEntity>();//工作流实例值List
            Dictionary<string, string> dicsp = new Dictionary<string, string>();

            #region 获取页面上的工作流实例值(wivList)
            if (null != ffeList)
            {
                foreach (FormFieldEntity item in ffeList)
                {
                    wivList.Add(new WfInsvalueEntity()
                    {
                        task_id = 0,
                        fieldName = item.name,
                        fieldType = item.fieldtype,
                        fieldValue = Request.Form[item.name],//等待小马的答复.
                    });
                    if (!string.IsNullOrEmpty(item.ifwfjudge))
                    {
                        dicsp.Add(item.ifwfjudge, Request.Form[item.name]);//将需要在wf中判断的字段存入dic中,传入启动的wf实例
                    }
                }
            }
            #endregion
            var platelist = System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>;
            WorkflowRuntimeManager manager = (System.Web.HttpContext.Current.Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager);
            {
                manager.WorkflowRuntime.StartRuntime();
                manager.MessageEvent += delegate(
                    Object sender1, WorkflowLogEventArgs e1)
                {
                    Console.WriteLine(e1.Message);
                };
                string ins_id = "INS" + CommonMethod.getUniqueid();
                foreach (var item in clrs)
                {
                    //UserEntity fqrEntity = bs.QueryUser(user.user.id);  //发起人就是当前用户
                    StartParameter sp = new StartParameter()
                    {
                        createrInfo = user.user,
                        insValue = dicsp,
                        wfName = wf_name,//界面上获取,默认demo
                        firstClr = new int[] { item },
                        clrid = item.ToString(),
                        sqlargs = sqlargs,
                        firstCllx = TaskClrType.由上一步处理人指定.ToString()
                    };

                    var resTag = wfs.DoWfStart(
                        manager, int.Parse(wftempid), int.Parse(wf_id), sp, wivList, platelist);
                    if (resTag.res)
                        return Content("操作失败");
                }
            }

            return RedirectToAction("PlanStartList");
        }

        #endregion
    }
}
